package vn.keho.module.dompeto.fragment;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bingkaimedia.merchantbeta.R;
import com.mobeta.android.dslv.DragSortController;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import vn.keho.module.dompeto.HomeActivity;
import vn.keho.module.dompeto.fragment.PageFragment.OnPageFragmentListener;
import vn.keho.module.dompeto.model.ChannelModel;


public class DSLVFragment extends ListFragment {

    private DompetoListAdapter adapter;

    private static Bitmap cardDefaultBitmap;

    private class DompetoListAdapter extends BaseAdapter {

        final private List<ChannelModel> listData;

        private DompetoListAdapter(List<ChannelModel> listData) {
            this.listData = listData;
        }

        @Override
        public int getCount() {
            return listData.size();
        }

        @Override
        public Object getItem(int i) {
            return listData.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                /*LayoutInflater mInflater = (LayoutInflater) getActivity()
                        .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
                convertView = mInflater.inflate(R.layout.list_item_handle_left, null);*/

                convertView = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.list_item_handle_left, null);
            }

            ChannelModel channelModel = listChannelModel.get(position);

            TextView txtChannelTitle = (TextView) convertView.findViewById(R.id.txtChannelTitle);
            ImageView imgCard = (ImageView) convertView.findViewById(R.id.drag_handle);
            ImageView imgClickRemove = (ImageView) convertView.findViewById(R.id.click_remove);
            if(channelModel.getChannelid().equals("false")) {
                txtChannelTitle.setVisibility(View.INVISIBLE);
                imgCard.setVisibility(View.INVISIBLE);
                imgClickRemove.setVisibility(View.INVISIBLE);
            } else {
                txtChannelTitle.setText(channelModel.getChanneltitle());
                // setting the image resource and title

                if(!HomeActivity.getInstance().isEditMode) {
                    imgClickRemove.setVisibility(View.INVISIBLE);
                } else {
                    imgClickRemove.setVisibility(View.VISIBLE);
                }

                txtChannelTitle.setVisibility(View.VISIBLE);
                imgCard.setVisibility(View.VISIBLE);
                convertView.setBackgroundResource(Color.TRANSPARENT);

                if(cardDefaultBitmap == null) {
                    cardDefaultBitmap = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.membercard);
                }
                Picasso.with(getActivity()).load(channelModel.getImageurl()).resize(cardDefaultBitmap.getWidth(), cardDefaultBitmap.getHeight()).centerInside().placeholder(R.drawable.membercard).into(imgCard);
            }
            return convertView;
        }

        public void remove(ChannelModel entry) {
            listData.remove(entry);
            notifyDataSetChanged();
        }

        public void insert(ChannelModel entry, int index) {
            listData.add(index, entry);
            entry.setSlotid(index + 1);
            notifyDataSetChanged();

            HomeActivity homeActivity = (HomeActivity) getActivity();
            homeActivity.onSyncWithServer();
        }

        public void clear(int index) {
            listData.remove(index);
            listData.add(index, new ChannelModel("false", index + 1));
            notifyDataSetChanged();

            HomeActivity homeActivity = (HomeActivity) getActivity();
            homeActivity.onSyncWithServer();
        }
    }

    private String[] array;
    private ArrayList<String> list;

    private WalletDragSortListView.DropListener onDrop =
            new WalletDragSortListView.DropListener() {
                @Override
                public void drop(int from, int to) {
                    if (from != to) {
                        ChannelModel channelModel = (ChannelModel)adapter.getItem(from);
                        adapter.remove(channelModel);
                        adapter.insert(channelModel, to);
                    }
                }
            };

    private WalletDragSortListView.RemoveListener onRemove =
            new WalletDragSortListView.RemoveListener() {
                @Override
                public void remove(int which) {
                    //ChannelModel channelModel = (ChannelModel)adapter.getItem(which);
                    adapter.clear(which);
                    Log.i("DSLVFragment", "onCliear ");
                }
            };

    protected int getLayout() {
        // this DSLV xml declaration does not call for the use
        // of the default DragSortController; therefore,
        // DSLVFragment has a buildController() method.
        return R.layout.dslv_fragment_main;
    }

    private WalletDragSortListView mDslv;
    private WalletDragSortController mController;

    public int dragStartMode = DragSortController.ON_DOWN;
    public boolean removeEnabled = false;
    public int removeMode = DragSortController.FLING_REMOVE;
    public boolean sortEnabled = true;
    public boolean dragEnabled = true;

    public List<ChannelModel> listChannelModel;

    public static DSLVFragment newInstance(List<ChannelModel> listChannelModel, int headers, int footers) {
        DSLVFragment f = new DSLVFragment();

        Bundle args = new Bundle();
        args.putInt("headers", headers);
        args.putInt("footers", footers);
        f.setArguments(args);
        f.listChannelModel = listChannelModel;
        return f;
    }

    public WalletDragSortController getController() {
        return mController;
    }

    /**
     * Called from DSLVFragment.onActivityCreated(). Override to
     * set a different adapter.
     */
    public void setListAdapter() {
        array = getResources().getStringArray(R.array.jazz_artist_names);
        list = new ArrayList<String>(Arrays.asList(array));

        //adapter = new ArrayAdapter<String>(getActivity(), getItemLayout(), R.id.text, list);
        adapter = new DompetoListAdapter(listChannelModel);
        setListAdapter(adapter);
    }

    /**
     * Called in onCreateView. Override this to provide a custom
     * DragSortController.
     */
    public WalletDragSortController buildController(WalletDragSortListView dslv) {
        // defaults are
        //   dragStartMode = onDown
        //   removeMode = flingRight
        WalletDragSortController controller = new WalletDragSortController(dslv);
        controller.setDragHandleId(R.id.drag_handle);
        controller.setClickRemoveId(R.id.click_remove);
        controller.setRemoveEnabled(removeEnabled);
        controller.setSortEnabled(sortEnabled);
        controller.setDragInitMode(dragStartMode);
        controller.setRemoveMode(removeMode);

        OnPageFragmentListener onPageFragmentListener = (OnPageFragmentListener) getActivity();
        controller.setPageFragmentListener(onPageFragmentListener);
        return controller;
    }


    /**
     * Called when the activity is first created.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mDslv = (WalletDragSortListView) inflater.inflate(getLayout(), container, false);

        mController = buildController(mDslv);
        mDslv.setFloatViewManager(mController);
        mDslv.setOnTouchListener(mController);
        mDslv.setDragEnabled(dragEnabled);

        return mDslv;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mDslv = (WalletDragSortListView) getListView();

        mDslv.setDropListener(onDrop);
        mDslv.setRemoveListener(onRemove);

        Bundle args = getArguments();
        int headers = 0;
        int footers = 0;
        if (args != null) {
            headers = args.getInt("headers", 0);
            footers = args.getInt("footers", 0);
        }

        for (int i = 0; i < headers; i++) {
            addHeader(getActivity(), mDslv);
        }
        for (int i = 0; i < footers; i++) {
            addFooter(getActivity(), mDslv);
        }

        setListAdapter();
    }


    public static void addHeader(Activity activity, WalletDragSortListView dslv) {
        LayoutInflater inflater = activity.getLayoutInflater();
        int count = dslv.getHeaderViewsCount();

        TextView header = (TextView) inflater.inflate(R.layout.header_footer, null);
        header.setText("Header #" + (count + 1));

        dslv.addHeaderView(header, null, false);
    }

    public static void addFooter(Activity activity, WalletDragSortListView dslv) {
        LayoutInflater inflater = activity.getLayoutInflater();
        int count = dslv.getFooterViewsCount();

        TextView footer = (TextView) inflater.inflate(R.layout.header_footer, null);
        footer.setText("Footer #" + (count + 1));

        dslv.addFooterView(footer, null, false);
    }

}
